<?php
/**
 * @package qBase
 * @subpackage regional
 *
 */

/**
 * QLanguages
 *
 * @package qBase
 * @subpackage regional
 */
class QLanguages extends QObject 
{
	private static $SupportedLanguages = array();

	private static $DefaultLanguage = null;
	private static $CurrentLanguage = null;
	private static $Data = array();
	
	public static $LanguageFile = null;
	public static $SendToJavaScript = false;
	
	public static function GetAllKeys()
	{
		return self::$Data;
	}
	
	public static function GetKey($key, $language = null)
	{
		if (!$language)
		{
			if (self::$CurrentLanguage)
				$language = self::$CurrentLanguage;
			else 
				$language = self::$DefaultLanguage;
		}
			
		if (!$language)
			throw new Exception("No language could be determined (check that the default language is defined)");
			
		if (!isset(self::$Data[$key]))
		{
			if (!self::$LanguageFile)
			{
				$r = mysql_fetch_assoc( mysql_query("SELECT `value_{$language}` FROM `LanguagesText` WHERE `key`='".mysql_real_escape_string($key)."'") );
				if ($r)
					self::$Data[$key][$language] = $r["value_{$language}"];
				else 
					self::$Data[$key][$language] = null;
			}
			else 
				throw new Exception("Can not find the translation for: {$key}");
		}
		
		return self::$Data[$key][$language];
	}
	
	public static function Get($key)
	{
		if (is_array($key))
		{
			$args = $key;
			$key = $args[0];
		}
		else 
			$args = func_get_args();
		
		$str = self::GetKey($key);
		$c_args = count($args);
		if ($c_args > 1)
		{
			for ($i = 1; $i < $c_args; $i++)
				$str = str_replace("{%".$i."}", $args[$i], $str);
		}

		return $str;
	}
	
	public static function SetLanguageFile($file, $include = true)
	{
		self::$LanguageFile = $file;
		if ($include)
			require_once($file);
	}
	
	public static function SetKey($key, $data = null)
	{
		if (is_array($key))
		{
			foreach ($key as $k => $d)
				self::$Data[$k] = $d;
		}
		else 
			self::$Data[$key] = $data;
	}
	
	public static function Out($key)
	{
		$params = func_get_args();
		echo self::Get($params);
	}
	
	public static function SetSupportedLanguages($languages)
	{
		self::$SupportedLanguages = $languages;
	}
	
	public static function SetDefaultLanguage($language)
	{
		self::$DefaultLanguage = $language;
	}
	
	public static function GetDefaultLanguage()
	{
		return self::$DefaultLanguage;
	}
	
	public static function GetLanguage()
	{
		return self::$CurrentLanguage;
	}
	
	public static function SetLanguage($language)
	{
		self::$CurrentLanguage = $language;
	}
	
	public static function GetFullData()
	{
		return self::$Data;
	}
}

?>